<?php
// +--------------------------------------------------------------------------------------------------------------------
// | 本文件是《FastChat》的一部分，所有代码、文字、图片、样式、风格等版权归作者所有，如有复制、仿冒、抄袭、盗用，FastAdmin和作者将追究法律责任
// +--------------------------------------------------------------------------------------------------------------------
// | @作者: 妙码生花 <1094963513@qq.com>
// +--------------------------------------------------------------------------------------------------------------------
// | @唯一授权链接: https://www.fastadmin.net/store/fastchat.html
// +--------------------------------------------------------------------------------------------------------------------

namespace addons\fastchat\library;

use think\Db;
use fast\Random;
use think\Config;

/**
 *
 */
class Chat
{
    /**
     * @var object 对象实例
     */
    protected static $instance;

    // 服务端连接实例
    protected $connection;

    // 发送消息使用的服务号
    protected $service_user;

    // 接受消息的用户
    protected $user;

    // 接受消息的管理员
    protected $admin;

    // 接受消息的用户组
    protected $user_group;

    // 接受消息的管理组
    protected $admin_group;

    // 错误消息
    protected $error;

    function __construct($service_user)
    {
        $this->service_user = $service_user;
        $fastchat_config    = get_addon_config('fastchat');
        $this->connection   = @stream_socket_client('tcp://127.0.0.1:' . ($fastchat_config['register_port'] + 100));

        if (!$this->connection) {
            $this->error = '内部推送通道连接失败,请确保Workerman服务已经启动！';
        }
    }

    /**
     * 初始化
     * @access public
     * @return Chat
     */
    public static function init($service_user = 1)
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($service_user);
        }

        return self::$instance;
    }

    public function user($data)
    {
        $this->user = $this->array_to_string($data);
        return $this;
    }

    /**
     * 解析数组为字符串，方便传输
     * @access public
     * @return string
     */
    public function array_to_string($data)
    {
        if (is_array($data)) {

            if (is_array(current($data))) {
                $this->error = '数组参数只能是一维数组！如 array(1,2,3)';
                return '';
            } else {
                $data = implode(',', $data);
            }
        }

        return trim($data, ',');
    }

    public function admin($data)
    {
        $this->admin = $this->array_to_string($data);
        return $this;
    }

    public function user_group($data)
    {
        $this->user_group = $this->array_to_string($data);
        return $this;
    }

    public function admin_group($data)
    {
        $this->admin_group = $this->array_to_string($data);
        return $this;
    }

    public function get_type(){
        return [1=>'报案',2=>'咨询',3=>'退费',4=>'理赔',5=>'催办',6=>'投诉'];
    }
    public function send($data,$ids,$admin)
    {
        if ($this->error) {
            return array('errcode' => -1, 'errmsg' => $this->error);
        }

        $service_user = Db::name('fastchat_service_user')
            ->where('id', $this->service_user)
            ->where('status', '1')
            ->where('deletetime', null)
            ->find();

        if (!$service_user) {
            return array('errcode' => -1, 'errmsg' => '服务账号不存在！');
        }

        // 准备服务号访问令牌
        $service_user['token'] = Random::uuid();

        // 加密 token
        $config = Config::get('token');
        $token  = hash_hmac($config['hashalgo'], $service_user['token'], $config['key']);

        Db::name('fastchat_service_user')
            ->where('id', $service_user['id'])
            ->update(['token' => $token]);

        $send_text = [
            'c'    => 'Message',
            'a'    => 'push_message',
            'data' => [
                'service_user' => $service_user['id'],
                'content'      => $data['content'],
                'user'         => $this->user,
                'admin'        => $this->admin,
                'user_group'   => $this->user_group,
                'admin_group'  => $this->admin_group,
                'token'        => $service_user['token'],
                'kf_id'        => $ids,
                'admin_id'     => $admin['id'],
                'admin_name'   => $admin['username'],
                'type'   => $this->get_type()[$data['type']],
            ]
        ];
        $send_text = json_encode($send_text) . "\n";

        if (fwrite($this->connection, $send_text) !== false) {
            fclose($this->connection);
            return array('errcode' => 0);
        }
    }
}